<template>
  <div>
    <el-card shadow="hover" style="margin-bottom: 10px">
      <div slot="header" class="clearfix">
        <span>货架信息管理</span>
        <el-button type="primary" size="mini" style="float: right" @click="handleAdd">
          <i class="el-icon-plus"></i> 添加货架
        </el-button>
      </div>
      <el-table v-loading="loading" :data="shelfList" style="width: 100%">
        <el-table-column prop="shelfId" label="货架ID" width="80" fixed="left"></el-table-column>
        <el-table-column prop="des" label="描述信息" show-overflow-tooltip></el-table-column>
        <el-table-column prop="layerNum" label="层数" width="80"></el-table-column>
        <el-table-column prop="cellNum" label="每层格数" width="100"></el-table-column>
        <el-table-column prop="leaderName" label="负责人" width="120"></el-table-column>
        <el-table-column prop="creatorName" label="创建人" width="120"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" :formatter="formatDateTime"></el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180" :formatter="formatDateTime"></el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row.shelfId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 15px; text-align: right">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 添加/编辑弹窗 -->
    <el-dialog :title="isEdit ? '编辑货架' : '添加货架'" :visible.sync="dialogVisible" width="500px" @close="handleCloseDialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="描述信息" prop="des">
          <el-input v-model="form.des" placeholder="请输入描述信息" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="货架层数" prop="layerNum">
          <el-input v-model.number="form.layerNum" placeholder="请输入货架层数" type="number"></el-input>
        </el-form-item>
        <el-form-item label="每层格数" prop="cellNum">
          <el-input v-model.number="form.cellNum" placeholder="请输入每层格数" type="number"></el-input>
        </el-form-item>
        <el-form-item label="负责人ID" prop="leader">
          <el-input v-model.number="form.leader" placeholder="请输入负责人ID" type="number"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import shelfApi from '@/api/shelf'

export default {
  name: 'DeviceShelf',
  data() {
    return {
      loading: false,
      submitLoading: false,
      shelfList: [],
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      dialogVisible: false,
      isEdit: false,
      form: {
        shelfId: null,
        des: '',
        layerNum: null,
        cellNum: null,
        leader: null
      },
      rules: {
        des: [
          { required: true, message: '请输入描述信息', trigger: 'blur' }
        ],
        layerNum: [
          { required: true, message: '请输入货架层数', trigger: 'blur' },
          { type: 'number', min: 1, message: '层数必须为正整数', trigger: 'blur' }
        ],
        cellNum: [
          { required: true, message: '请输入每层格数', trigger: 'blur' },
          { type: 'number', min: 1, message: '格数必须为正整数', trigger: 'blur' }
        ],
        leader: [
          { required: true, message: '请输入负责人ID', trigger: 'blur' },
          { type: 'number', message: '负责人ID必须为数字', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchShelfList()
  },
  methods: {
    async fetchShelfList() {
      this.loading = true
      try {
        const params = {
          pageNum: this.pagination.pageNum,
          pageSize: this.pagination.pageSize
        }
        const res = await shelfApi.getShelfList(params)
        const body = res.data

        if (body.code === 200 && body.data && body.data.page) {
          this.shelfList = body.data.page.records || []
          this.pagination.total = body.data.page.total || 0
        } else {
          this.shelfList = []
          this.pagination.total = 0
          this.$message.error(body.message || '获取货架列表失败')
        }
      } catch (error) {
        this.shelfList = []
        this.pagination.total = 0
        console.error('获取货架列表失败:', error)
        this.$message.error('获取货架列表失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    formatDateTime(row, column, cellValue) {
      if (!cellValue) return ''
      return new Date(cellValue).toLocaleString()
    },
    resetForm() {
      this.form = {
        shelfId: null,
        des: '',
        layerNum: null,
        cellNum: null,
        leader: null
      }
    },
    handleCloseDialog() {
      this.$refs.form.clearValidate()
      this.resetForm()
    },
    handleAdd() {
      this.isEdit = false
      this.resetForm()
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.isEdit = true
      this.form = { 
        shelfId: row.shelfId,
        des: row.des,
        layerNum: row.layerNum,
        cellNum: row.cellNum,
        leader: row.leaderID
      }
      this.dialogVisible = true
    },
    handleSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.submitLoading = true
          try {
            if (this.isEdit) {
              const payload = {
                shelfId: this.form.shelfId,
                des: this.form.des,
                // The API doc for update requires 'operator'
                operator: this.form.leader
              }
              await shelfApi.updateShelf(payload)
              this.$message.success('更新成功')
            } else {
              const payload = {
                des: this.form.des,
                layerNum: this.form.layerNum,
                cellNum: this.form.cellNum,
                leader: this.form.leader
              }
              await shelfApi.addShelf(payload)
              this.$message.success('添加成功')
            }
            this.dialogVisible = false
            this.fetchShelfList()
          } catch (error) {
            console.error('操作失败:', error)
            const errorMessage = error.response?.data?.message || '操作失败'
            this.$message.error(errorMessage)
          } finally {
            this.submitLoading = false
          }
        }
      })
    },
    handleDelete(shelfId) {
      this.$confirm('确定要删除该货架信息吗？此操作不可撤销。', '警告', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await shelfApi.deleteShelf(shelfId)
          this.$message.success('删除成功')
          if (this.shelfList.length === 1 && this.pagination.pageNum > 1) {
            this.pagination.pageNum--
          }
          this.fetchShelfList()
        } catch (error) {
          console.error('删除货架失败:', error)
          const errorMessage = error.response?.data?.message || '删除失败'
          this.$message.error(errorMessage)
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.pageNum = 1
      this.fetchShelfList()
    },
    handleCurrentChange(val) {
      this.pagination.pageNum = val
      this.fetchShelfList()
    }
  }
}
</script>

<style scoped>
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}
</style>
